package com.yunfeng.supercall.activity;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.LauncherActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lin.action.UIDfineAction;
import com.lin.utils.DatabaseHelperForChattingMap;
import com.lin.utils.Parameters;
import com.lin.utils.Session;
import com.lin.utils.Session.ResultReceiver;
import com.ly.quickdev.library.utils.JsonUtils;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.ContactsBaseBean;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.manager.SuperFriendsManager;
import com.yzx.api.UCSCall;

/**
 * 来电页面
 */
public class InCallActivity extends BaseCallActivity {

	//*******************
	/*private LinearLayout remotelayout,locallayout;*/

	public String mNumber;
	private Handler mHandler = new Handler();
	private View mAnswer, mHangUp;
	private Button mButtonHangUp;
	private TextView mTextViewNumber;
	private NotificationManager mNM;
	/*	private ImageButton converse_call_mute;
	private ImageButton converse_call_video;
	private ImageButton converse_call_speaker;
	private ImageButton converse_call_switch;*/
	private boolean open_headset=false;
	private boolean closeVideo = false;
	private boolean isAnswer = false;
	Session mSession;
	int mCallId;
	int callid = -10;
	
	int curState = -2;
	int prevState = -2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		mSession = Session.getSession();
		
		Parameters.isInCalling = true;
		mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		setContentView(R.layout.activity_in_call);
		UCSCall.setSpeakerphone(true);
		mTextViewNumber = findView(R.id.number);
		mNumber = getIntent().getStringExtra("number");
		mAnswer = findViewById(R.id.answer);
		mHangUp = findViewById(R.id.hang_up);
		mTextViewState = (TextView) findViewById(R.id.textview_state);
		mButtonHangUp = findView(R.id.btn_hang_up);
		SuperFriendsManager manager = (SuperFriendsManager) ManagerFactory
				.createManager(SuperFriendsBean.class);
		mTextViewlevel = (TextView) findViewById(R.id.level);

		try {
			mFriends = manager.findSuperFriendsByYZXNumber(mNumber);
		} catch(NullPointerException e) {
			try{
				mDatabase = new DatabaseHelperForChattingMap(getApplicationContext(), "db", 2);
				mFriends = mDatabase.getSuperFriendsBeanByVoId(mNumber);
			} catch(NullPointerException e2) {
				if(MainActivity.isForeground == true) {
					Intent intent2= new Intent(this, MainActivity.class);
					startActivity(intent2);
				} else {
					Intent intent2= new Intent(this, LoginActivity.class);
					startActivity(intent2);
				}
			} finally {
				mDatabase.close();
			}
		}
		super.setmSuperFriends(mFriends);


		if (mFriends != null) {

			ContactsBaseBean.setupDoubleLineContactsView(
					findViewById(R.id.contacts_area), mFriends);
			if (mFriends.getSucolor() == 0) {
				mTextViewNumber.setText(mFriends.getWhiteSuperNumber());
			} else {
				mTextViewNumber.setText(mFriends.getSuperNumber());
				// mTextViewNumber.setText(ContactsDialPadAdapter
				// .replaceTextColor(mFriends.getPhone(),
				// mFriends.getPhone(), mFriends));
			}
		} else {
			searchFriends(mNumber);
			// ((TextView) findView(R.id.tv)).setText(mNumber);
		}
		UCSCall.startRinging(true);
		mSession = Session.getSession();
		mSession.setCreateCallRecord(getApplicationContext(), mSession.getmUserBean().getUserid() + "", mFriends.getUserid() + "", new ResultReceiver<Integer>() {

			@Override
			public void onResult(boolean last, Integer args) {
				// TODO Auto-generated method stub
				callid = args;
			}
			
		});
		
		/*IntentFilter ift2 = new IntentFilter();
		ift2.addAction(UIDfineAction.ACTION_DIAL_STATE);
		ift2.addAction(UIDfineAction.ACTION_ANSWER);
		ift2.addAction(UIDfineAction.ACTION_CALL_TIME);
		ift2.addAction(UIDfineAction.ACTION_NETWORK_STATE);
		ift2.addAction("android.intent.action.HEADSET_PLUG");
		registerReceiver(br, ift2);*/
		//		sendBroadcast(new Intent(Constants.ACTION_RECEIVE_MSG2));
		/*remotelayout = (LinearLayout) findViewById(R.id.remotelayout);			
		locallayout = (LinearLayout) findViewById(R.id.locallayout);
		UCSCall.initCameraConfig(InCallActivity.this, remotelayout, locallayout);
		UCSCall.refreshCamera(UCSCameraType.REMOTECAMERA);*/
		//		converse_information.setText("视频电话来电");
	}

	private void searchFriends(String phone) {
		JSONObject json = BaseActivity.getBaseParams(getActivity());
		try {
			json.put("i_key", phone);
			json.put("i_type", 0);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_SEARCH_USER, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				try {

					sendBroadcast(new Intent(ACTION_UPDATE_CALL));
					SuperFriendsBean mSuperFriends = JsonUtils.parse(
							data.substring(1, data.length() - 1),
							SuperFriendsBean.class);
					InCallActivity.this.setmSuperFriends(mSuperFriends);
					ContactsBaseBean.setupDoubleLineContactsView(
							findViewById(R.id.contacts_area), mSuperFriends);
					mTextViewlevel.setText(getLevel(mSuperFriends.getLevel()));
					if (mSuperFriends.getSucolor() == 0) {
						mTextViewNumber.setText(mSuperFriends
								.getWhiteSuperNumber());
					} else {
						mTextViewNumber.setText(mSuperFriends.getSuperNumber());
						// mTextViewNumber.setText(ContactsDialPadAdapter
						// .replaceTextColor(mFriends.getPhone(),
						// mFriends.getPhone(), mFriends));
					}

					setLevelColor(mSuperFriends.getLevel(), mTextView, mTextViewNumber);
					refreshView(mSuperFriends);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					showToast(R.string.super_number_not_found);
				}
			}

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub

			}
		});
	}

	//不用这个启动会很耗时间	
	Handler mHandlerSendBroadcast = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			sendBroadcast(new Intent(Constants.ACTION_RECEIVE_MSG2));
		}

	};

	@Override
	public void onBackPressed() {
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Parameters.isInCalling = false;
		mSession.setOverCallRecord(getApplicationContext(), mCallId + "", new ResultReceiver<Integer>(){

			@Override
			public void onResult(boolean last, Integer args) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		/*		 if(br != null) {
				getActivity().unregisterReceiver(br);
				br = null;

			}*/

	}

	@Override
	public void onAnswer() {
		// TODO Auto-generated method stub
		super.onAnswer();
		mTextView.setText(R.string.call_busy);
		mTextViewState.setText(R.string.call_busy);
		UCSCall.setSpeakerphone(false);
		startCountUp();
	}

	private boolean hasAnswer;
	private TextView mTextViewState;
	private TextView mTextViewlevel;
	private SuperFriendsBean mFriends;
	private DatabaseHelperForChattingMap mDatabase;

	@Override
	public void onHangUp() {
		// TODO Auto-generated method stub
		super.onHangUp();
		mTextViewState.setText("挂断");
	}

	@Override
	public void onOtherHangUp() {
		// TODO Auto-generated method stub
		mTextViewState.setText("对方挂断");
		showNotificationPersonal("您有一个未接来电","您有一个未接来电");

	}

	private void showNotificationPersonal(String title, String content) {


		//		Intent[] mIntents = new Intent[1];
		int currentapiVersion = android.os.Build.VERSION.SDK_INT;
		Intent mIntents = new Intent(this, LauncherActivity.class);
		/*		if (currentapiVersion > 10) {
			mIntents[0] = new Intent(this, LauncherActivity.class);


		}*/


		PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, mIntents, PendingIntent.FLAG_UPDATE_CURRENT);
		Notification notification = null;
		try {

			notification = new NotificationCompat.Builder(
					getApplicationContext())
			.setContentTitle(title)
			.setContentIntent(pendingIntent).setContentText(content + "")
			.setSmallIcon(R.drawable.ic_launcher)

			.setWhen(System.currentTimeMillis()).setAutoCancel(true)
			.build();

			notification.contentIntent = PendingIntent.getActivity(
					this,
					300,
					new Intent(this, MainActivity.class).putExtra(
							Constants.KEY_DATA, new SuperFriendsBean()).addFlags(
									Intent.FLAG_ACTIVITY_SINGLE_TOP),
									PendingIntent.FLAG_UPDATE_CURRENT);

		} catch (Exception e) {
			notification = new NotificationCompat.Builder(
					getApplicationContext())
			.setContentTitle(title).setContentIntent(pendingIntent)
			.setContentText(content + "")
			.setSmallIcon(R.drawable.ic_launcher)
			.setWhen(System.currentTimeMillis()).setAutoCancel(true)
			.getNotification();

			notification.contentIntent = PendingIntent.getActivity(
					this,
					300,
					new Intent(this, MainActivity.class).putExtra(
							Constants.KEY_DATA, new SuperFriendsBean()).addFlags(
									Intent.FLAG_ACTIVITY_SINGLE_TOP),
									PendingIntent.FLAG_UPDATE_CURRENT);
		}

		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		notification.flags |= Notification.DEFAULT_VIBRATE;

		notification.defaults=Notification.DEFAULT_SOUND;
		// Send the notification.
		// We use a string id because it is a unique number. We use it later to
		// cancel.
		try {
			mNM.notify("service_created", 10, notification);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	public void answer(View v) {
		startListenSensor();
		UCSCall.answer("");
		startAnimation();
		UCSCall.stopRinging();
		hasAnswer = true;
		// UCSCall.setSpeakerphone(true);
	}

	public void hangUp(View v) {
		UCSCall.hangUp("");
		UCSCall.stopRinging();
		addCallTime();
		stopCountUp();
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				finish();
			}
		}, 1000);
	}

	private void startAnimation() {
		mAnswer.startAnimation(AnimationUtils.loadAnimation(getActivity(),
				R.anim.push_out_right_to_left));
		mButtonHangUp.startAnimation(AnimationUtils.loadAnimation(
				getActivity(), R.anim.push_in_down_to_up));
		mHangUp.startAnimation(AnimationUtils.loadAnimation(getActivity(),
				R.anim.push_out_left_to_right));
		mAnswer.setVisibility(View.GONE);
		mHangUp.setVisibility(View.GONE);
		mButtonHangUp.setVisibility(View.VISIBLE);
	}

	String getLevel(int level){
		String levelS = null;
		switch(level) {
		case 1:levelS="新诞生";break;
		case 2:levelS="吃奶尿床";break;
		case 3:levelS="断奶吃饭";break;
		case 4:levelS="说学走";break;
		case 5:levelS="幼儿园";break;
		case 6:levelS="小学生";break;
		case 7:levelS="初中生";break;
		case 8:levelS="高中生";break;
		case 9:levelS="大学生";break;
		case 10:levelS="硕士";break;
		default:levelS="博士";break;
		}
		return levelS;
	}

	void setLevelColor(int level,TextView tvUserName, TextView tvPhone, TextView tvLevel) {
		try {

			if(level == 0) {
				tvPhone.setTextColor(getResources().getColor(R.color.white));
				tvUserName.setTextColor(getResources().getColor(R.color.white));
				tvLevel.setTextColor(getResources().getColor(R.color.white));

			} else if(level == 1) {
				tvPhone.setTextColor(getResources().getColor(R.color.level_or));
				tvUserName.setTextColor(getResources().getColor(R.color.level_or));
				tvLevel.setTextColor(getResources().getColor(R.color.level_or));
			} else {
				tvPhone.setTextColor(getResources().getColor(R.color.level_red));
				tvUserName.setTextColor(getResources().getColor(R.color.level_red));
				tvLevel.setTextColor(getResources().getColor(R.color.level_red));
			}
		} catch(NullPointerException e) {

		}
	}


	/*private BroadcastReceiver br = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(UIDfineAction.ACTION_DIAL_STATE)){
				int state = intent.getIntExtra("state", 0);
//				CustomLog.i(DfineAction.TAG_TCP, "VIDEO_CALL_STATE:"+state);
				if(UIDfineAction.dialState.keySet().contains(state)){
//					converse_information.setText(UIDfineAction.dialState.get(state));
				}
				if(state == UCSCall.CALL_VOIP_RINGING_180){
					UCSCall.startCallRinging("dialling_tone.pcm");
				}else {
					UCSCall.stopRinging();
					UCSCall.stopCallRinging();
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							InCallActivity.this.finish();
						}
					}, 1000);
				}
			}else if(intent.getAction().equals(UIDfineAction.ACTION_ANSWER)){
				isAnswer=true;
				AudioManager mAudioManager = ((AudioManager) getSystemService(Context.AUDIO_SERVICE));
		        if(mAudioManager.isWiredHeadsetOn()){
		        	converse_call_speaker.setBackgroundResource(R.drawable.converse_speaker);
		        	UCSCall.setSpeakerphone(false);
		        }else {
		        	converse_call_speaker.setBackgroundResource(R.drawable.converse_speaker_down);
		        	UCSCall.setSpeakerphone(true);
				}
				UCSCall.stopCallRinging();
				UCSCall.stopRinging();
				locallayout.setVisibility(View.VISIBLE);
	        	remotelayout.setVisibility(View.VISIBLE);
	        	converse_call_mute.setVisibility(View.VISIBLE);
	        	converse_call_video.setVisibility(View.VISIBLE);
	        	converse_call_speaker.setVisibility(View.VISIBLE);
	        	converse_call_switch.setVisibility(View.VISIBLE);
//	        	video_call_answer.setVisibility(View.GONE);
	        	open_headset = true;
	        	//刷新远程摄像，重要，一定要加这个
	        	mHandler.sendEmptyMessageDelayed(2, 1000);
	        	sendBroadcast(new Intent(UIDfineAction.ACTION_START_TIME));
			}else if(intent.getAction().equals(UIDfineAction.ACTION_CALL_TIME)){
				String timer = intent.getStringExtra("timer");
				if(converse_information != null){
					converse_information.setText(timer);
				}
			}else if(intent.getAction().equals(UIDfineAction.ACTION_NETWORK_STATE)){
				switch (intent.getIntExtra("state", 0)) {
				case 0:
					converse_network.setText("网络质量一般");
					break;
				case 1:
					converse_network.setText("网络质量好");
					break;
				case 2:
					converse_network.setText("网络质量差");
					break;
				default:
					if(!isAnswer){
						converse_information.setText("无网络");
						UCSCall.stopRinging();
						UCSCall.stopCallRinging();
						new Handler().postDelayed(new Runnable() {
							@Override
							public void run() {
								VideoConverseActivity.this.finish();
							}
						}, 1000);
						break;
					}
				}
			}else if(intent.getAction().equals("android.intent.action.HEADSET_PLUG")){
				//发现个别手机会接通电话前收到这个广播并把扬声器打开了，所以open_headset作为判断必须接通后再接收耳机插拔广播才有效
				if(intent.getIntExtra("state", 0) == 1 && open_headset){
//					CustomLog.e(DfineAction.TAG_TCP,"Speaker false");
					converse_call_speaker.setBackgroundResource(R.drawable.converse_speaker);
					UCSCall.setSpeakerphone(false);
                }else if(intent.getIntExtra("state", 0) == 0 && open_headset){
//                	CustomLog.e(DfineAction.TAG_TCP,"Speaker true");
                	converse_call_speaker.setBackgroundResource(R.drawable.converse_speaker_down);
                    UCSCall.setSpeakerphone(true);
                }   
			}
		}
	};*/
	
	
	private Handler mHanderPeriod = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			mHanderPeriod.sendEmptyMessageDelayed(0, 3000);
			mSession.setUpdateCallRecord(getApplicationContext(), callid, mSession.getmUserBean().getUserid(), new ResultReceiver<Integer>() {

				@Override
				public void onResult(boolean last, Integer args) {
					// TODO Auto-generated method stub
					prevState = curState;
					curState = args;
				}
				
			});
			
		}

	};

}
